package com.edu.controller.book;

import com.edu.dto.ResultDto;
import com.edu.entity.BookEntity;
import com.edu.service.BookService;
import com.edu.service.impl.BookServiceImpl;

import com.edu.utils.JwtUtils;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * com.edu.controller.book
 * 2024/7/4 21:15
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet("/books/*")
public class BookByIdController extends HttpServlet {
    BookService bookService = new BookServiceImpl();

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookId = req.getPathInfo().substring(1);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        //从请求头获取token
        String token = req.getHeader("token");
        //返回当前操作用户的基本信息
        Map<String, Object> user = JwtUtils.validateToken(token);

        try {
            //验证是否为管理员操作
            if(user != null && user.get("role").equals("admin")){
                Integer resultRow = bookService.deleteBookInfo(bookId);

                if (resultRow >= 1) {
                    String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Book information delete successfully.");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                } else {
                    String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "书籍不存在");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                }
            } else {
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "权限不足");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 获取用户id
        String bookId = req.getPathInfo().substring(1);
        System.out.println("获取到的用户id: " + bookId);

        // 根据用户id查询用户信息
        HashMap<String, Object> userInfo = bookService.getBookInfoById(bookId);

        if (userInfo != null) {
            String rst = ResultDto.success(userInfo);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "获取书籍信息失败。书籍id无效。");
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(rst);
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookId = req.getPathInfo().substring(1);
        BookEntity book = ServletHelper.getRequestBodyAsObject(req, BookEntity.class);
        book.setBookId(Integer.parseInt(bookId));
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        //从请求头获取token
        String token = req.getHeader("token");
        //返回当前操作用户的基本信息
        Map<String, Object> user = JwtUtils.validateToken(token);



        try {
            //验证是否为管理员操作
            if(user != null && user.get("role").equals("admin")){
                Integer resultRow = bookService.updateBookInfo(book);

                if (resultRow >= 1) {
                    String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Book information updated successfully.");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                } else {
                    String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "更新失败。输入的信息有误或书籍不存在。");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                }
            } else {
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "权限不足");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

}
